<template>
  <div class="history-container">
    <div class="header-section">
      <h2 class="page-title">我的AIGC降重处理记录</h2>
      <p class="subtitle">查看您的所有文件</p>
    </div>

    <el-card class="files-list-card" shadow="always">
      <div class="table-header">
        <div class="left-section">
<!--          <el-input-->
<!--              placeholder="搜索文件名称..."-->
<!--              prefix-icon="Search"-->
<!--              v-model="searchQuery"-->
<!--              clearable-->
<!--              class="search-input"-->
<!--              @input="handleSearch"-->
<!--          />-->
        </div>
        <div class="right-section">
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </div>
      </div>

      <el-table
          :data="fileRecords"
          style="width: 100%"
          stripe
          border
          :empty-text="'暂无文件记录'"
          highlight-current-row
          row-class-name="table-row"
          header-row-class-name="table-header-row"
      >
        <el-table-column prop="fileName" label="文件名" min-width="240">
          <template #default="{ row }">
            <div class="file-name-cell">
              <el-icon class="file-icon" :color="getFileIconColor(row.fileType)">
                <component :is="getFileIcon(row.fileType)" />
              </el-icon>
              <span class="file-name-text">{{ row.fileName }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="fileType" label="类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag
                :type="getFileTypeTagType(row.fileType)"
                :effect="getTagEffect(row.fileType)"
                class="custom-file-tag"
            >
              <div class="tag-content">
                <el-icon class="tag-icon"><Document /></el-icon>
                <span>{{ row.fileType.toUpperCase() }}</span>
              </div>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="fileSize" label="文件大小" width="120" align="center">
          <template #default="{ row }">
            <div class="size-badge">{{ formatFileSize(row.fileSize) }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="上传时间" width="180" align="center">
          <template #default="{ row }">
            <div class="time-display">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDateTime(row.createdAt) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="下载文件" placement="top" :enterable="false">
                <el-button type="primary" circle @click="downloadFile(row)">
                  <el-icon><Download /></el-icon>
                </el-button>
              </el-tooltip>
<!--              <el-tooltip content="重新处理" placement="top" :enterable="false">-->
<!--                <el-button type="success" circle @click="processAgain(row)">-->
<!--                  <el-icon><Refresh /></el-icon>-->
<!--                </el-button>-->
<!--              </el-tooltip>-->
<!--              <el-tooltip content="查看详情" placement="top" :enterable="false">-->
<!--                <el-button type="info" circle @click="showDetails(row)">-->
<!--                  <el-icon><View /></el-icon>-->
<!--                </el-button>-->
<!--              </el-tooltip>-->
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalRecords"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </el-card>

    <!-- 文件详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="文件详情"
        width="50%"
        top="8vh"
        destroy-on-close
        class="custom-dialog"
    >
      <file-detail :file="currentFile" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadFile(currentFile)">
            <el-icon><Download /></el-icon> 下载文件
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 没有记录时的提示 -->
    <div v-if="fileRecords.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无文件记录">
        <el-button type="primary" @click="$router.push('/')">快去降重吧!</el-button>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script>
import { Document, Download, Refresh, View, Calendar, Search } from '@element-plus/icons-vue'
import FileDetail from './FileDetailsView.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = import.meta.env.VITE_GATEWAY_URL || 'http://localhost:8080';

export default {
  components: { Document, Download, Refresh, View, Calendar, FileDetail },
  data() {
    return {
      fileRecords: [],
      currentPage: 1,
      pageSize: 10,
      totalRecords: 0,
      detailDialogVisible: false,
      currentFile: null,
      userId: sessionStorage.getItem('userId'),
      loading: true,
      searchQuery: ''
    }
  },
  created() {
    this.fetchFileRecords()
  },
  methods: {
    async fetchFileRecords() {
      this.loading = true;
      try {
        const response = await axios.get('/fileDb/getFilesByUserId', {
          params: {
            userId: this.userId,
            page: this.currentPage,
            pageSize: this.pageSize,
            keyword: this.searchQuery
          }
        })
        this.fileRecords = response.data.records
        this.totalRecords = response.data.total
      } catch (error) {
        this.handleError(error, '获取文件记录失败')
      } finally {
        this.loading = false;
      }
    },
    getFileIcon(fileType) {
      const iconMap = {
        'doc': 'Document',
        'docx': 'Document',
        'pdf': 'Document',
        'txt': 'Document',
        'xlsx': 'Document'
      }
      return iconMap[fileType.toLowerCase()] || 'Document'
    },
    getFileIconColor(fileType) {
      const colorMap = {
        'doc': '#2b5797',
        'docx': '#2b5797',
        'pdf': '#d24726',
        'txt': '#666666',
        'xlsx': '#217346'
      }
      return colorMap[fileType.toLowerCase()] || '#999999'
    },
    getFileTypeTagType(fileType) {
      const typeMap = {
        'doc': '',
        'docx': 'primary',
        'pdf': 'danger',
        'txt': 'info',
        'xlsx': 'success'
      }
      return typeMap[fileType.toLowerCase()] || 'info'
    },
    getTagEffect(fileType) {
      // 根据文件类型返回不同的效果
      const typeMap = {
        'doc': 'plain',
        'docx': 'dark',
        'pdf': 'plain',
        'txt': 'light',
        'xlsx': 'dark'
      }
      return typeMap[fileType.toLowerCase()] || 'light';
    },
    async downloadFile(file) {
      if (!file) return;

      ElMessage({
        message: '正在准备下载...',
        type: 'info',
        duration: 2000
      });

      if (file.fileCategory === 'GENERATED') {
        try {
          const getUrlRes = await axios.get(`/file/getUrl/${file.ossKey}`);
          if (getUrlRes.status === 200) {
            const fileURL = getUrlRes.data;
            console.log('获取到的文件 URL:', fileURL);
            window.open(fileURL, '_blank');
            ElMessage.success('文件准备完成，正在打开下载链接');
          } else {
            ElMessage.error('获取文件 URL 失败');
          }
        } catch (error) {
          this.handleError(error);
        }
      } else if (file.taskId) {
        try {
          const res = await axios.get('/aigc/paper-pass-info', {
            params: { id: file.taskId }
          });
          if (res.data.code === 1) {
            const contentUrl = res.data.data.content_url;
            if (contentUrl) {
              window.open(contentUrl, '_blank');
              ElMessage.success('报告准备完成，正在打开查看链接');
            } else {
              ElMessage.warning('结果 URL 为空');
            }
          } else {
            ElMessage.error(res.data.msg || '获取结果详情失败');
          }
        } catch (error) {
          this.handleError(error);
        }
      } else {
        ElMessage.warning('任务 ID 为空，无法获取结果');
      }
    },
    processAgain(file) {
      console.log('再次处理文件:', file.fileName);
      // 实际处理逻辑
      ElMessage({
        message: '重新处理请求已提交',
        type: 'success',
        duration: 2000
      });
    },
    showDetails(file) {
      this.currentFile = file;
      this.detailDialogVisible = true;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchFileRecords();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchFileRecords();
    },
    formatFileSize(size) {
      if (size < 1024) {
        return `${size} B`;
      } else if (size < 1024 * 1024) {
        return `${(size / 1024).toFixed(2)} KB`;
      } else {
        return `${(size / (1024 * 1024)).toFixed(2)} MB`;
      }
    },
    formatDateTime(dateTime) {
      return new Date(dateTime).toLocaleString();
    },
    handleError(error, message = '请求出错，请稍后重试') {
      console.error('请求出错:', error);
      ElMessage.error(message);
    },
    refreshData() {
      this.fetchFileRecords();
      ElMessage({
        message: '数据刷新成功',
        type: 'success',
        duration: 1500
      });
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchFileRecords();
    }
  }
}
</script>

<style scoped>
.history-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  background: linear-gradient(120deg, #3a86ff, #58a7ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.files-list-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.files-list-card:hover {
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 6px 0;
}

.file-icon {
  font-size: 24px;
  filter: drop-shadow(1px 1px 2px rgba(0, 0, 0, 0.2));
}

.file-name-text {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.custom-file-tag {
  border-radius: 6px;
  padding: 6px 12px;
  font-weight: 600;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  font-size: 0.9em;
}

.custom-file-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.tag-content {
  display: flex;
  align-items: center;
  gap: 5px;
}

.tag-icon {
  font-size: 14px;
}

.size-badge {
  background-color: #f5f7fa;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 0.85em;
  font-weight: 500;
  color: #606266;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.time-display {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.action-buttons .el-button {
  transition: all 0.3s;
}

.action-buttons .el-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.custom-dialog :deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  margin: 0;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.table-row {
  transition: all 0.2s;
}

.table-row:hover td {
  background-color: #ecf5ff !important;
}

.table-header-row th {
  background-color: #f5f7fa !important;
  color: #333;
  font-weight: 600;
}

.empty-state {
  margin-top: 40px;
  text-align: center;
}

.loading-state {
  margin-top: 20px;
}

/* 响应式样式调整 */
@media (max-width: 768px) {
  .history-container {
    padding: 20px 10px;
  }

  .table-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .right-section {
    display: flex;
    justify-content: flex-end;
  }

  .action-buttons {
    gap: 6px;
  }

  .action-buttons .el-button {
    padding: 6px;
  }

  .custom-dialog {
    width: 95% !important;
  }

  .page-title {
    font-size: 24px;
  }

  .subtitle {
    font-size: 14px;
  }
}
</style>